import { defineStore } from 'pinia'
import { 
  getUserOrders, 
  getOrderDetails, 
  createOrder, 
  generateDownloadToken, 
  verifyDownloadToken,
  getAllOrders,
  updateOrderStatus
} from '@/api/order'

export const useOrderStore = defineStore('order', {
  state: () => ({
    userOrders: [],
    currentOrder: null,
    downloadToken: null,
    adminOrders: [],
    loading: false,
    error: null
  }),

  getters: {
    getUserOrders: (state) => state.userOrders,
    getCurrentOrder: (state) => state.currentOrder,
    getDownloadToken: (state) => state.downloadToken,
    getAdminOrders: (state) => state.adminOrders,
    isLoading: (state) => state.loading,
    getError: (state) => state.error
  },

  actions: {
    // 重置错误状态
    resetError() {
      this.error = null
    },

    // 获取用户订单列表
    async fetchUserOrders(params) {
      this.loading = true
      this.resetError()
      
      try {
        const response = await getUserOrders(params)
        this.userOrders = response.data
        return response.data
      } catch (error) {
        console.error('获取用户订单列表失败:', error)
        this.error = error.message || '获取用户订单列表失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取订单详情
    async fetchOrderDetails(orderNumber) {
      this.loading = true
      this.resetError()
      
      try {
        const response = await getOrderDetails(orderNumber)
        this.currentOrder = response.data
        return response.data
      } catch (error) {
        console.error('获取订单详情失败:', error)
        this.error = error.message || '获取订单详情失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建新订单
    async submitOrder(orderData) {
      this.loading = true
      this.resetError()
      
      try {
        const response = await createOrder(orderData)
        return response.data
      } catch (error) {
        console.error('创建订单失败:', error)
        this.error = error.message || '创建订单失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 生成下载令牌
    async getDownloadToken(orderNumber) {
      this.loading = true
      this.resetError()
      
      try {
        const response = await generateDownloadToken(orderNumber)
        this.downloadToken = response.data.token
        return response.data.token
      } catch (error) {
        console.error('生成下载令牌失败:', error)
        this.error = error.message || '生成下载令牌失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 验证下载令牌
    async validateDownloadToken(orderNumber, token) {
      this.loading = true
      this.resetError()
      
      try {
        const response = await verifyDownloadToken(orderNumber, token)
        return response.data.valid
      } catch (error) {
        console.error('验证下载令牌失败:', error)
        this.error = error.message || '验证下载令牌失败'
        return false
      } finally {
        this.loading = false
      }
    },

    // 管理员：获取所有订单
    async fetchAllOrders(params) {
      this.loading = true
      this.resetError()
      
      try {
        const response = await getAllOrders(params)
        this.adminOrders = response.data
        return response.data
      } catch (error) {
        console.error('获取所有订单失败:', error)
        this.error = error.message || '获取所有订单失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    // 管理员：更新订单状态
    async changeOrderStatus(orderNumber, status) {
      this.loading = true
      this.resetError()
      
      try {
        const response = await updateOrderStatus(orderNumber, status)
        
        // 更新本地状态
        if (this.currentOrder && this.currentOrder.orderNumber === orderNumber) {
          this.currentOrder.status = status
        }
        
        // 更新用户订单列表中的状态
        const userOrder = this.userOrders.find(order => order.orderNumber === orderNumber)
        if (userOrder) {
          userOrder.status = status
        }
        
        // 更新管理员订单列表中的状态
        const adminOrder = this.adminOrders.find(order => order.orderNumber === orderNumber)
        if (adminOrder) {
          adminOrder.status = status
        }
        
        return response.data
      } catch (error) {
        console.error('更新订单状态失败:', error)
        this.error = error.message || '更新订单状态失败'
        throw error
      } finally {
        this.loading = false
      }
    }
  }
})